import { Component, OnInit } from '@angular/core';
import { UploadFile } from 'ng-zorro-antd';
import { HttpClient, HttpRequest, HttpResponse } from '@angular/common/http';
import { filter } from 'rxjs/operators';
import { opusimgagesUrl, opusUrl, fileUrl } from '../../../urlConfig';
import { HttpService } from '../../../service/httpService/http.service';
import { LocalStorageService } from '../../../service/localStorageService/local-storage.service';
import { NzNotificationService, NzMessageService } from 'ng-zorro-antd';
import { Router } from '@angular/router';

import moment from 'moment/src/moment.js'
import 'moment/src/locale/zh-cn.js' // 时间中文显示


@Component({
  selector: 'app-upload',
  templateUrl: './upload.component.html',
  styleUrls: ['./upload.component.styl']
})
export class UploadComponent implements OnInit {

  data = {
    title: '', // 作品标题
    partakeAdd: [], // 作品成员
    synopsis: '', // 作品简介
    code: '',// 源码仓库
    cover: '', // 封面图
    content: '',// 内容
    date: '', //发布时间
    accessToken: '',
  }

  fileList = []; // 存放封面图
  uploading = false;
  isSpinning: boolean = false; // 上传动画
  newpartakeAdd: any[] = []; // 添加成员转换后的格式
  imgName: string = ''; // 存放封面图
  visible = false; // 抽屉控制

  showUploadList = { // 框架带的放大图片控制
    showPreviewIcon: true,
    showRemoveIcon: true,
    hidePreviewIconInNonImage: true
  };
  imgList = [
    {
      uid: -1,
      name: 'xxx.png',
      status: 'done',
      url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
    }
  ];

  constructor(private http1: HttpClient,
    public http: HttpService,
    public localStorage: LocalStorageService,
    private notification: NzNotificationService,
    public router: Router,
    private message: NzMessageService
  ) { }
  ngOnInit() {
    // 获取自身持有的图片
    this.http.getData(fileUrl).subscribe((event: any) => {
      if (event.code === 200) {
        this.imgList = event.data;

      }
    })
  }
  // 添加成员
  partakeAddMethod() {
    this.data.partakeAdd.forEach((currentValue, index) => {
      if (currentValue.partakeTxt === '') {
        this.data.partakeAdd.splice(index, 1);
      }
    })
    this.data.partakeAdd.push({
      partakeTxt: ''
    })
  }
  // 成员删除
  partakeDel(index) {
    this.data.partakeAdd.splice(index, 1);
  }
  // 作品发布
  submit() {
    var content: string = localStorage.getItem('tinymce-autosave-/home/upload-myTextarea-draft');
    this.data.content = content;
    this.data.accessToken = this.localStorage.getItem('token').accessToken
    this.format();
    this.data.partakeAdd = this.newpartakeAdd;
    this.data.cover = this.imgName;
    this.data.date = moment().format('YYYY-MM-DD HH:mm:ss');
    this.http.postData(opusUrl, this.data).subscribe((event: any) => {
      if (event.code === 200) {
        this.isSpinning = false;
        this.empty();
        this.createMessage('success');
        this.router.navigate(['/home/individualopus']);
      }
    })
  }

  beforeUpload = (file: UploadFile): boolean => {
    this.fileList = this.fileList.concat(file);
    return false;
  };

  // 封面图上传
  handleUpload() {

    const token: any = this.localStorage.getItem('token');
    const formData = new FormData();
    this.fileList.forEach((file: any) => {
      formData.append('files[]', file);
    });
    formData.append('accessToken', token.accessToken);
    this.uploading = true;
    const flag = this.validationField();

    if (flag) { // 判断所有输入框是否满足要求
      if (this.fileList.length !== 0) {  // 判断是否上传图片

        this.isSpinning = true;

        const req = new HttpRequest('POST', opusimgagesUrl, formData, {
        });
        this.http1
          .request(req)
          .pipe(filter(e => e instanceof HttpResponse))
          .subscribe((event: any) => {  // 成功回调
            this.uploading = false;
            this.fileList = [];
            if (event.body.data.filename) {
              this.imgName = event.body.data.filename; // 返回的图片链接
              this.submit();
            }
          },
            (error: any) => {// 失败回调
              this.isSpinning = false;
              this.resetUpdateImage("error");
            }
          );
      } else {
        this.updateImage("error");
      }

    } else {
      this.createNotification("error");
    }

  }

  // 转换嵌套格式
  format() {
    this.data.partakeAdd.forEach((currentValue, index) => {
      this.newpartakeAdd[index] = currentValue.partakeTxt
    })
  }

  // 清空数据
  empty() {
    const data = this.data;
    data.title = '';
    data.partakeAdd = [];
    data.synopsis = '';
    data.code = '';
    data.cover = '';
    data.content = '';
    data.accessToken = '';
    this.localStorage.removeItem('tinymce-autosave-/home/upload-myTextarea-draft');
  }

  //  验证字段
  validationField(): boolean {
    const data = this.data;
    if (data.title.length > 5 && data.synopsis.length > 10 && data.code !== null
      && data.content !== null && data.partakeAdd.length !== 0) {
      // 清空多余的参与成员输入框
      this.data.partakeAdd.forEach((currentValue, index) => {
        if (currentValue.partakeTxt === '') {
          this.data.partakeAdd.splice(index, 1);
        }
      })
      return true;
    } else {
      return false;
    }
  }


  open(): void {
    this.visible = true;
  }

  close(): void {
    this.visible = false;
  }


  previewImage: string | undefined = '';
  previewVisible = false;


  handlePreview = (file: UploadFile) => {
    console.log(file);
    
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  };



  // 警告框
  createNotification(type: string): void {
    this.notification.create(
      type,
      '上传失败',
      '请按照要求填入所有输入项！！！'
    );
  }

  // 警告框
  updateImage(type: string): void {
    this.notification.create(
      type,
      '上传失败',
      '请上传封面图！！！'
    );
  }

  // 警告框
  resetUpdateImage(type: string): void {
    this.notification.create(
      type,
      '封面图上传失败',
      '请重新上传封面图！！！'
    );
  }
  // 全局提示框
  createMessage(type: string): void {
    this.message.create(type, `发布成功`);
  }
}
